package com.zy.web.service.impl;

import com.zy.common.helper.LoginHelper;
import com.zy.common.utils.sql.StringUtils;
import com.zy.common.core.page.TableDataInfo;
import com.zy.common.core.domain.PageQuery;
import com.zy.web.domain.ZyCompetition;
import com.zy.web.domain.bo.ZyCompetitionBo;
import com.zy.web.domain.bo.ZyRanksBo;
import com.zy.web.domain.vo.ZyRanksVo;
import com.zy.web.repository.ZyCompetitionRepository;
import com.zy.web.repository.ZyRanksRepository;
import com.zy.web.service.IZyRanksService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import com.zy.web.domain.ZyRanks;
import org.springframework.data.domain.Page;
import org.springframework.data.jpa.domain.Specification;

import javax.persistence.criteria.Predicate;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 队伍Service业务层处理
 *
 * @author zy
 * @date 2024-02-25
 */
@RequiredArgsConstructor
@Service
public class ZyRanksServiceImpl implements IZyRanksService {

    private final ZyRanksRepository repository;

    /**
     * 查询队伍
     */
    @Override
    public ZyRanksVo queryById(String id) {
        return repository.findById(id).map(v -> com.zy.common.utils.BeanCopyUtils.copy(v, ZyRanksVo.class)).orElse(null);
    }

    /**
     * 查询队伍列表
     */
    @Override
    public TableDataInfo<ZyRanksVo> queryPageList(ZyRanksBo bo, PageQuery pageQuery) {
        Page<ZyRanks> result = repository.findAll(getSpecification(bo), pageQuery.pageable());
        return TableDataInfo.build(result, ZyRanksVo.class);
    }

    /**
     * 查询当前用户的队伍列表
     */
    @Override
    public TableDataInfo<ZyRanksVo> queryPageListCurr(ZyRanksBo bo, PageQuery pageQuery) {
        Page<ZyRanks> result = repository.findAll(getSpecificationCurr(bo), pageQuery.pageable());
        return TableDataInfo.build(result, ZyRanksVo.class);
    }

    private Specification<ZyRanks> getSpecificationCurr(ZyRanksBo bo) {
        return (root, query, cb) -> {
            List<Predicate> predicates = new ArrayList<>();
            if (StringUtils.isNotBlank(bo.getId())) {
                predicates.add(cb.equal(root.get("id"), bo.getId()));
            }
            if (bo.getCreateBy() != null) {
                predicates.add(cb.equal(root.get("createBy"), bo.getCreateBy()));
            }
            if (bo.getCreateTime() != null) {
                predicates.add(cb.equal(root.get("createTime"), bo.getCreateTime()));
            }
            if (bo.getUpdateBy() != null) {
                predicates.add(cb.equal(root.get("updateBy"), bo.getUpdateBy()));
            }
            if (bo.getUpdateTime() != null) {
                predicates.add(cb.equal(root.get("updateTime"), bo.getUpdateTime()));
            }
            if (StringUtils.isNotBlank(bo.getDwmc())) {
                predicates.add(cb.equal(root.get("dwmc"), bo.getDwmc()));
            }
            if (StringUtils.isNotBlank(bo.getCjr())) {
                predicates.add(cb.equal(root.get("cjr"), bo.getCjr()));
            }
            if (StringUtils.isNotBlank(bo.getLxfs())) {
                predicates.add(cb.equal(root.get("lxfs"), bo.getLxfs()));
            }

            //查询所有的id和csry
            List<ZyRanksRepository.IdAndCsry> allIdAndCsry = repository.findAllIdAndCsz();
            List<String> ids = new ArrayList<>(); //当前用户的队伍列表的ids
            for (ZyRanksRepository.IdAndCsry idAndCsry : allIdAndCsry) {
                String csz = idAndCsry.getCsry();
                if (csz==null) continue; //该队伍还没有参赛人员
                List<String> cszList = Arrays.asList(csz.split(","));
                if (cszList.contains(LoginHelper.getLoginUser().getUsername())) { //队伍中的人员包含当前用户
                    ids.add(idAndCsry.getId());
                }
            }
            predicates.add(root.get("id").in(ids));
            return query.where(predicates.toArray(new Predicate[predicates.size()])).getRestriction();
        };
    }

    /**
     * 查询队伍列表
     */
    @Override
    public List<ZyRanksVo> queryList(ZyRanksBo bo) {
        return repository.findAll(getSpecification(bo)).stream()
                .map(v -> com.zy.common.utils.BeanCopyUtils.copy(v, ZyRanksVo.class))
                .collect(Collectors.toList());
    }

    private Specification<ZyRanks> getSpecification(ZyRanksBo bo) {
        return (root, query, cb) -> {
            Map<String, Object> params = bo.getParams();
            List<Predicate> predicates = new ArrayList<>();
            if (StringUtils.isNotBlank(bo.getId())) {
                predicates.add(cb.equal(root.get("id"), bo.getId()));
            }
            if (bo.getCreateBy() != null) {
                predicates.add(cb.equal(root.get("createBy"), bo.getCreateBy()));
            }
            if (bo.getCreateTime() != null) {
                predicates.add(cb.equal(root.get("createTime"), bo.getCreateTime()));
            }
            if (bo.getUpdateBy() != null) {
                predicates.add(cb.equal(root.get("updateBy"), bo.getUpdateBy()));
            }
            if (bo.getUpdateTime() != null) {
                predicates.add(cb.equal(root.get("updateTime"), bo.getUpdateTime()));
            }
            if (StringUtils.isNotBlank(bo.getDwmc())) {
                predicates.add(cb.equal(root.get("dwmc"), bo.getDwmc()));
            }
            if (StringUtils.isNotBlank(bo.getCjr())) {
                predicates.add(cb.equal(root.get("cjr"), bo.getCjr()));
            }
            if (StringUtils.isNotBlank(bo.getLxfs())) {
                predicates.add(cb.equal(root.get("lxfs"), bo.getLxfs()));
            }
            if (StringUtils.isNotBlank(bo.getCsry())) {
                predicates.add(cb.equal(root.get("csry"), bo.getCsry()));
            }
            return query.where(predicates.toArray(new Predicate[predicates.size()])).getRestriction();
        };
    }

    /**
     * 新增队伍
     */
    @Override
    public Boolean insertByBo(ZyRanksBo bo) {
        ZyRanks add = com.zy.common.utils.BeanCopyUtils.copy(bo, ZyRanks.class);
        validEntityBeforeSave(add);
        repository.saveAndFlush(add);
        bo.setId(add.getId());
        return true;
    }

    /**
     * 修改队伍
     */
    @Override
    public Boolean updateByBo(ZyRanksBo bo) {
        ZyRanks update = com.zy.common.utils.BeanCopyUtils.copy(bo, ZyRanks.class);
        validEntityBeforeSave(update);
        return repository.save(update) != null;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(ZyRanks entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除队伍
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        repository.deleteAllById(ids);
        return true;
    }

}
